package com.right.handler;

import com.right.command.CsCommand;
import com.right.db.BicycleLock;
import com.right.factory.NodeStatus;
import com.right.mapper.BicycleLockMapper;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * <pre>
 *     @author : pillar
 *     e-mail : 347637454@qq.com
 *     time   : 2018/12/19 16:39
 *     desc   :
 *     version: 1.0
 * </pre>
 */
@Slf4j
public class HeartHandler implements PackageHandler {


    private final BicycleLockMapper bicycleLockMapper;

    public HeartHandler(BicycleLockMapper bicycleLockMapper) {
        this.bicycleLockMapper = bicycleLockMapper;
    }

    @Override
    public boolean applies(List<String> dataList) {
        return CsCommand.HEAR.equals(dataList.get(0));
    }

    @Override
    public boolean handleMessage(ChannelHandlerContext ctx, List<String> dataList) {
        log.info("心跳={}", dataList);

        String lockNo = ctx.channel().attr(NodeStatus.LOCK_NO).get();

        // 查询锁类型
        Example example = new Example(BicycleLock.class);

        example.createCriteria().andEqualTo("lockNo", lockNo);

        BicycleLock bicycleLock = bicycleLockMapper.selectOneByExample(example);

        // 更新电压值和更新时间
        String voltage = dataList.get(1);
        bicycleLock.setVoltage(Long.parseLong(voltage));
        bicycleLock.setUpdated_at(new Date());

        bicycleLockMapper.updateByPrimaryKey(bicycleLock);

        return false;
    }
}
